import json

from django.http import JsonResponse

from lapi_app.models.testcase_model.testcase import Testcase
from lapi_app.models.testcase_model.testcase_tree import Menu


# 添加，重命名目录树
from lapi_app.models.ui_model.ui_case import UI_case


def add_edit_tree(request):
    body = request.body
    data = json.loads(body)
    label = data["label"]
    pid = data["pid"]
    t = data["type"]
    u = data["user_id"]
    if label == '' or pid == '' or t == '' or u == '':
        return JsonResponse({'code': 100, 'message': "参数不能为空"})
    else:
        if "id" not in data.keys():
            if Menu.objects.filter(label=label).count() > 1:
                return JsonResponse({'code': 101, 'message': "名称已存在，请重新输入"})
            elif t == 1 or t == '1' or t == 3 or t == '3':
                menu = Menu.objects.create(label=label, pid=pid, type=t, m_user_id=u)
                return JsonResponse(
                    {'code': 200, 'message': "添加成功", "data": {"id": menu.id, "type": t, "label": label, "pid": pid}})
            elif t == 2 or t == '2' or t == 4 or t == '4':
                if t == 2 or t == '2':
                    case = Testcase.objects.create(t_name=label, t_user_id=u)
                    menu = Menu.objects.create(label=label, pid=pid, type=t, m_user_id=u, testcase_id=case.id)
                    return JsonResponse(
                        {'code': 200, 'message': "添加成功",
                         "data": {"id": menu.id, "type": t, "label": label, "pid": pid}})
                elif t == 4 or t == '4':
                    case = UI_case.objects.create(user_id=u)
                    menu = Menu.objects.create(label=label, pid=pid, type=t, m_user_id=u, ui_id=case.id)
                    return JsonResponse(
                        {'code': 200, 'message': "添加成功",
                         "data": {"id": menu.id, "type": t, "label": label, "pid": pid}})
        elif Menu.objects.filter(label=label).count() > 1:
            return JsonResponse({'code': 101, 'message': "名称已存在，请重新输入"})
        else:
            Menu.objects.filter(id=data["id"]).update(label=label)
            Testcase.objects.filter(id=Menu.objects.get(id=data["id"]).testcase_id).update(t_name=label)
            return JsonResponse({'code': 200, 'message': "重命名成功", "id": data["id"], "label": label})


# 拖拽改变层级
def change_pid(request):
    try:
        data = json.loads(request.body)
        from_id = data["from_id"]
        to_id = data["to_id"]
        if to_id is None or from_id is None:
            return JsonResponse({'code': 100, 'message': "参数不能为空"})
        else:
            Menu.objects.filter(id=from_id).update(pid=to_id)
            return JsonResponse({'code': 200, 'message': "更换层级成功"})
    except Exception as e:
        return JsonResponse({'code': 100, 'message': str(e)})
